package com.mashibing.service;

import com.mashibing.constant.CommonStatusEnum;
import com.mashibing.dto.PassengerUser;
import com.mashibing.dto.ResponseResult;
import com.mashibing.mapper.PassengerUserMapper;
import com.mashibing.request.VerificationCodeRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private PassengerUserMapper passengerUserMapper;
    public ResponseResult loginOrReg(@RequestBody VerificationCodeRequest verificationCodeRequest){

        /**
         * 1、接收手机号
         * 2、检查手机号是否在数据库中是否存在
         *      1、存在就获取
         *      2、不存在就插入
         */
        //1、接收手机号
        String passengerPhone = verificationCodeRequest.getPassengerPhone();
        Map<String,Object> map = new HashMap<>();
        map.put("passenger_phone",passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);
       // 2、检查手机号是否在数据库中是否存在
        if (passengerUsers.size()==0) {
            //  2、不存在就插入
            PassengerUser passengerUser = new PassengerUser();
            passengerUser.setPassengerPhone(passengerPhone);
            passengerUser.setPassengerName("李坤朋");
            passengerUser.setPassengerGender((byte) 0);
            passengerUser.setState((byte) 0);
            LocalDateTime now = LocalDateTime.now();
            passengerUser.setGmtModified(now);
            passengerUser.setGmtCreate(now);
            passengerUser.setProfilePhoto("https://lw-math-plus.oss-cn-shanghai.aliyuncs.com/avatar/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F/%E7%94%A8%E6%88%B7%E5%A4%B4%E5%83%8F.png");
            passengerUserMapper.insert(passengerUser);
        }else {
        }


        return ResponseResult.success();
    }

    /**
     * 根据手机号查询用户基本信息
     * 1、根据手机号向数据库中查询信息
     * @param passengerPhone
     * @return
     */
    public ResponseResult getUserByPhone(String passengerPhone) {
        // 1、根据手机号向数据库中查询信息
        Map<String,Object> map = new HashMap<>();
        map.put("passenger_phone",passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);

        // 如果未查询到
        if (passengerUsers.size() == 0) {
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXIST.getCode(),CommonStatusEnum.USER_NOT_EXIST.getMessage());
        }
        // 查询到
        PassengerUser passengerUser = passengerUsers.get(0);
        return ResponseResult.success(passengerUser);
    }
}
